package org.dromara.web.weixin.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.XcxLoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.vo.FXcxUserVo;
import org.dromara.system.service.IFXcxUserService;
import org.dromara.system.service.ISysUserService;
import org.dromara.web.weixin.bo.AuthBo;
import org.dromara.web.weixin.vo.XcxUserInfo;
import org.springframework.web.bind.annotation.*;


/**
 * ClassName:xcxController
 * Package:org.dromara.web.weixin.api
 * Date:2024/3/27 15:57
 * Description:
 * Author:zsm@zhangshuming.com
 */
@RestController
@RequestMapping("xcx")
@RequiredArgsConstructor
@SaIgnore
public class xcxController {
    private final WxMaService wxMaService;
    private final IFXcxUserService xcxUserService;
    private final ISysUserService sysUserService;


   /* @GetMapping("getAssessToken")
    public void getAssessToken(String appId){
        if (!wxMaService.switchover(appId)){
            throw new ServiceException("配置不存在:" + appId);
        }
        String assessToken = null;
        try {
            assessToken = wxMaService.getAccessToken();
            Console.log(assessToken);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }*/

    @PostMapping("auth") // 更新头像名称手机号
    private R<Void> auth(@RequestBody AuthBo authBo) {
        if (xcxUserService.updateUser(
            authBo.getNikename(),
            authBo.getAvatar(),
            authBo.getPhoneEncryptedData(),
            authBo.getPhoneIv(),
            authBo.getXcxCode(),
            authBo.getProvince(),
            authBo.getCity())
            .getData()) {
            return R.ok("授权成功");
        }
        return R.fail("授权失败");
    }

    @GetMapping("getXcxUserInfo") // 获取用户信息
    public R<XcxUserInfo> getXcxUserInfo() {
        XcxLoginUser loginUser = (XcxLoginUser) LoginHelper.getLoginUser();
        if (ObjectUtil.isNull(loginUser)){
            return R.fail("用户未登录");
        }
        Long userId = loginUser.getUserId();
        FXcxUserVo xcxUserVo = xcxUserService.queryById(userId);
        XcxUserInfo userInfo = new XcxUserInfo();
        userInfo.setFXcxUserVo(xcxUserVo);
        userInfo.setPermissions(loginUser.getMenuPermission());
        userInfo.setRoles(loginUser.getRolePermission());
        return R.ok("获取成功", userInfo);
    }
}
